package luanvan.app.foodnote;


import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import luanvan.app.foodnote.library.GooglePlaces;
import luanvan.app.foodnote.library.JSONParser;
import luanvan.app.foodnote.library.Place;
import luanvan.app.foodnote.library.PlacesList;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Window;


public class LocationActivity extends FragmentActivity  {
	// Draw circle
	private static final double EARTH_RADIUS = 6378100.0;
    private int offset;
    
	PlacesList nearPlaces;
	GooglePlaces googlePlaces;
	private GoogleMap mMap1;
	
	SupportMapFragment supportMapFragment;
	// Map overlay items
	
	LatLng toPosition;
	//AddItemizedOverlay itemizedOverlay;
	
	ProgressDialog pDialog;
	
	Double latitude;
	Double longitude;
	
	// JSON parser class
    JSONParser jsonParser = new JSONParser();
	
	//private static final String url_food_detials = "http://10.0.2.2/foodnote/get_food_details.php";
	
    private static final String TAG_LATITUDE = "LATITUDE";
    private static final String TAG_LONGITUDE = "LONGITUDE";
    
    double lat, lng;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.form_map);

        Intent i = getIntent();
        lat = i.getExtras().getDouble(TAG_LATITUDE);
        lng = i.getExtras().getDouble(TAG_LONGITUDE);
        Log.d("Location Extra", String.valueOf(lat) + ", " + String.valueOf(lng));
        if(lat != 0.0 && lng != 0.0){
	        supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapview);
	        
	        mMap1 = supportMapFragment.getMap();
	        
	        LatLng coordinates = new LatLng(lat, lng);
	        mMap1.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 14)); 
	        
	        mMap1.addCircle(new CircleOptions().center(new LatLng(lat, lng)).radius(1000).strokeColor(Color.RED)
	        		.strokeWidth(3));
	        mMap1.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Vị trí món ăn"));
		        
	        
	        //mMap1.addMarker(new MarkerOptions().position(coordinates).title("Vị trí món ăn"));
		        
	        //mMap1.addCircle(new Ci);
	        
	       new LoadPlaces().execute(lat, lng);
        }
	}
	
	class LoadPlaces extends AsyncTask<Double, String, String>{

		double lat2, lng2;
		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LocationActivity.this);
            pDialog.setTitle("Please wait");
            pDialog.setMessage("Đang tải các địa điểm ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
	 	
		@Override
		protected String doInBackground(Double... args) {
			lat2 = args[0];
			lng2 = args[1];
			googlePlaces = new GooglePlaces();
			
			try {
				String types = "cafe|food|restaurant"; // Listing places only cafes, restaurants, foods restaurant|
				 
                // Radius in meters - increase this value if you don't find any places
                double radius = 1000;
				nearPlaces = googlePlaces.search(lat2, lng2, radius, types);
				
			} catch(Exception e){
				e.printStackTrace();
			}
			
			//PlacesList places = null;
			
			return null;
		}
		protected void onPostExecute(String file_url) {
	        // dismiss the dialog after getting all products
	        pDialog.dismiss();
	        
	        runOnUiThread(new Runnable() {
				
				public void run() {
					if(nearPlaces.results != null){
				        
				        /*if(nearPlaces.results != null){*/
				        	for(Place place : nearPlaces.results){
				        		latitude = place.geometry.location.lat;
				        		longitude = place.geometry.location.lng;
				        		
				        		toPosition = new LatLng(latitude, longitude);
				        		
				        		mMap1.addMarker(new MarkerOptions().position(toPosition).title(place.name)
				        				.snippet(place.vicinity).icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_blue)));
				        		
				        	}
					
					} // End if nearPlaces.results
				}
			});
		}
	}
	
	// convert meters to pixels between 2 points in current zoom:

    private int convertMetersToPixels(double lat, double lng, double radiusInMeters) {

         double lat1 = radiusInMeters / EARTH_RADIUS;
         double lng1 = radiusInMeters / (EARTH_RADIUS * Math.cos((Math.PI * lat / 180)));

         double lat2 = lat + lat1 * 180 / Math.PI;
         double lng2 = lng + lng1 * 180 / Math.PI; 

         Point p1 = supportMapFragment.getMap().getProjection().toScreenLocation(new LatLng(lat, lng));
         Point p2 = supportMapFragment.getMap().getProjection().toScreenLocation(new LatLng(lat2, lng2));

         return Math.abs(p1.x - p2.x);
    }
    
    private Bitmap getBitmap() {

        // fill color
        Paint paint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint1.setColor(0x110000FF);
        paint1.setStyle(Style.FILL);

        // stroke color
        Paint paint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint2.setColor(0xFF0000FF);
        paint2.setStyle(Style.STROKE);

        // icon
        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.mark_red);

        // circle radius - 200 meters
        int radius = offset = convertMetersToPixels(lat, lng, 1000);

        // if zoom too small
        if (radius < icon.getWidth() / 2) {

            radius = icon.getWidth() / 2;
        }

        // create empty bitmap 
        Bitmap b = Bitmap.createBitmap(radius * 2, radius * 2, Config.ARGB_8888);
        Canvas c = new Canvas(b);

        // draw blue area if area > icon size
        if (radius != icon.getWidth() / 2) {

            c.drawCircle(radius, radius, radius, paint1);
            c.drawCircle(radius, radius, radius, paint2);
        }

        // draw icon
        c.drawBitmap(icon, radius - icon.getWidth() / 2, radius - icon.getHeight() / 2, new Paint());

        return b;
    }
    // calculate image offset:

    private LatLng getCoords(double lat, double lng) {

        LatLng latLng = new LatLng(lat, lng);

        Projection proj = supportMapFragment.getMap().getProjection();
        Point p = proj.toScreenLocation(latLng);
        p.set(p.x, p.y + offset);

        return proj.fromScreenLocation(p);
    }

}
